import {
  AmbientLight,
  Color,
  Material,
  MeshLambertMaterial,
  MeshPhongMaterial,
  PointLight,
  Texture,
} from "three";
import {
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
  Mesh,
  BoxBufferGeometry,
  MeshBasicMaterial,
  TextureLoader,
  GridHelper,
  AxesHelper,
  SphereBufferGeometry,
} from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

let camera: PerspectiveCamera, scene: Scene, renderer: WebGLRenderer;
let mesh: Mesh;
let mesh1: Mesh;
let control: OrbitControls;
let materials: Array<any> = [];

init();
animate();
function init() {
  camera = new PerspectiveCamera(
    70,
    window.innerWidth / window.innerHeight,
    1,
    1000
  );
  camera.position.set(50, 50, 50);

  scene = new Scene();

  // 添加光源
  let ambientLight = new AmbientLight("#fff", 0.1);
  let pointLight = new PointLight("#fff", 0.5);
  pointLight.position.set(100, 100, 100);
  scene.add(ambientLight);
  scene.add(pointLight);

  // 添加辅助系统
  let axes = new AxesHelper(100);
  let grid = new GridHelper(100);
  scene.add(axes);
  scene.add(grid);

  /**
   * 1: 添加发光小球
   */
  let sphere1 = new SphereBufferGeometry(10, 100, 100);
  let material1 = new MeshPhongMaterial({
    color: "#ffffff",
    transparent: true,
    opacity: 0.6,
    emissive: "#f00",
    shininess: 1,
  });
  materials.push(material1);
  mesh = new Mesh(sphere1, material1);
  mesh.position.y = 10;
  scene.add(mesh);

  /**
   * 2：添加纹理小球
   */
  let sphere2 = new SphereBufferGeometry(10, 10, 10);
  let texture = new Texture(generateTexture());
  texture.needsUpdate = true;
  let material2 = new MeshLambertMaterial({
    transparent: true,
    map: texture,
  });
  mesh1 = new Mesh(sphere2, material2);
  mesh1.position.set(20, 10, 0);
  scene.add(mesh1);

  renderer = new WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  control = new OrbitControls(camera, renderer.domElement);
  // renderer.render(scene, camera);
}

function animate() {
  requestAnimationFrame(animate);

  const timer = 0.0001 * Date.now();

  materials[0].emissive.setHSL(0, 1, 0.35 * (0.5 + 0.5 * Math.sin(35 * timer)));
  mesh1.rotateX(.03)
  mesh1.rotateY(.02)

  renderer.render(scene, camera);
}

function generateTexture() {
  const canvas = document.createElement("canvas");
  canvas.width = 256;
  canvas.height = 256;

  const context = canvas.getContext("2d");
  const image = context.getImageData(0, 0, 256, 256);

  let x = 0,
    y = 0;

  for (let i = 0, j = 0, l = image.data.length; i < l; i += 4, j++) {
    x = j % 256;
    y = x === 0 ? y + 1 : y;

    image.data[i] = 255;
    image.data[i + 1] = 255;
    image.data[i + 2] = 255;
    image.data[i + 3] = Math.floor(x ^ y);
  }

  context.putImageData(image, 0, 0);

  return canvas;
}
